package com.qys.livesMall.shop.event.handle.service;

import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.shop.event.handle.BaseHandler;
import com.qys.livesMall.shop.event.shop.pojo.ShopOrderPojo;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuStocksMapper;
import com.qys.livesMall.shop.modal.entity.*;
import com.qys.livesMall.shop.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @menu ShopOrderServer
 * @date 2023/11/06 14:37
 */
@Slf4j
@Service
public class ShopOrderServer implements BaseHandler<ShopOrderPojo> {

    @Autowired
    private ShopOrderSkuService shopOrderSkuService;

    @Autowired
    private H2ShopStatisticsInfoService shopStatisticsInfoService;

    @Autowired
    private ShopStatisticsEverydayService shopStatisticsEverydayService;

    @Autowired
    private ShopGoodsSkuStocksMapper skuStocksMapper;

    @Autowired
    private ShopGoodsSkuService shopGoodsSkuService;

    @Autowired
    private ShopGoodsInfoService shopGoodsInfoService;

    @Override
    public void correct(Long shopId) {
        Integer orderNum=shopOrderSkuService.getOrderNum(shopId, LocalDateTime.MIN,LocalDateTime.MAX);
        H2ShopStatisticsInfo shopStatisticsInfo=shopStatisticsInfoService.getField(shopId, H2ShopStatisticsInfo::getId, H2ShopStatisticsInfo::getOrderNumber);
        shopStatisticsInfo.setOrderNumber(orderNum);
        shopStatisticsInfoService.updateById(shopStatisticsInfo);
    }

    @Override
    public void handle(ShopEventInfo<ShopOrderPojo> info) {
        List<ShopOrderSku> skus=shopOrderSkuService.getPriceByOrderId(info.getParamObj().getOrderId());
        if (CollectionUtils.isEmpty(skus)){
            return;
        }
        Map<Long,List<ShopOrderSku>> skuMap=skus.stream().collect(Collectors.groupingBy(ShopOrderSku::getShopId));
        for(Long shopId:skuMap.keySet()){
            List<ShopOrderSku> shopSkus=skuMap.get(shopId);
            BigDecimal totalPrice=BigDecimal.ZERO;
            Integer totalNum=0;
            for(ShopOrderSku sku:shopSkus) {
                totalPrice = totalPrice.add(sku.getPrice().multiply(new BigDecimal(sku.getNum())));
                totalNum = totalNum + sku.getNum();
            }
//
            ShopStatisticsEveryDay shopStatisticsEveryday=shopStatisticsEverydayService.getField(shopId, LocalDate.now(),ShopStatisticsEveryDay::getId, ShopStatisticsEveryDay::getOrderNum,ShopStatisticsEveryDay::getSalesVolume,ShopStatisticsEveryDay::getSalesAmount);
            if (shopStatisticsEveryday==null){
                shopStatisticsEveryday=new ShopStatisticsEveryDay();
                shopStatisticsEveryday.setShopId(shopId);
                shopStatisticsEveryday.setDataDate(LocalDate.now());
                shopStatisticsEveryday.setOrderNum(0);
                shopStatisticsEveryday.setSalesVolume(0);
                shopStatisticsEveryday.setSalesAmount(BigDecimal.ZERO);
            }
            shopStatisticsEveryday.setOrderNum((shopStatisticsEveryday.getOrderNum()==null?0:shopStatisticsEveryday.getOrderNum())+1);
            shopStatisticsEveryday.setSalesVolume((shopStatisticsEveryday.getSalesVolume()==null?0:shopStatisticsEveryday.getSalesVolume())+totalNum);
            shopStatisticsEveryday.setSalesAmount((shopStatisticsEveryday.getSalesAmount()==null?BigDecimal.ZERO:shopStatisticsEveryday.getSalesAmount()).add(totalPrice));
            shopStatisticsEverydayService.saveOrUpdate(shopStatisticsEveryday);

            H2ShopStatisticsInfo shopStatisticsInfo=shopStatisticsInfoService.getField(shopId,H2ShopStatisticsInfo::getId, H2ShopStatisticsInfo::getOrderNumber,H2ShopStatisticsInfo::getSalesVolume,H2ShopStatisticsInfo::getSalesAmount);
            shopStatisticsInfo.setOrderNumber((shopStatisticsInfo.getOrderNumber()==null?0:shopStatisticsInfo.getOrderNumber())+1);
            shopStatisticsInfo.setSalesVolume((shopStatisticsInfo.getSalesVolume()==null?0:shopStatisticsInfo.getSalesVolume())+totalNum);
            shopStatisticsInfo.setSalesAmount((shopStatisticsInfo.getSalesAmount()==null?BigDecimal.ZERO:shopStatisticsInfo.getSalesAmount()).add(totalPrice));
            //库存变动，直接查询实时数据，订单退回时不减下单量，数据无法对其
            //库存量 库存额
            Map<String,Object> stock= skuStocksMapper.getStockNumAndAmount(shopId);
            if (stock!=null){
                shopStatisticsInfo.setStocksNum(stock.get("num")!=null?Integer.valueOf(stock.get("num").toString()):0);
                shopStatisticsInfo.setStocksAmount(stock.get("amount")!=null?(BigDecimal) stock.get("amount"):BigDecimal.ZERO);
            }
            shopStatisticsInfoService.updateById(shopStatisticsInfo);
        }
        try{
            handleSkuStockOp(skus.stream().map(ShopOrderSku::getSkuId).collect(Collectors.toList()));
        }catch (Exception e){
            log.error("判断下架商品错误："+e);
        }
    }

    private void handleSkuStockOp(List<Long> shopSkuIds){
        List<ShopGoodsSku> skus=shopGoodsSkuService.listByIds(shopSkuIds);
        List<Long> shopGoodsIds= skus.stream().map(ShopGoodsSku::getShopGoodsId).collect(Collectors.toList());
        for (Long shopGoodsId:shopGoodsIds){
            List<Long> skuIds=shopGoodsSkuService.getSkuIdsByGoodsId(shopGoodsId);
            Integer num= skuStocksMapper.getNumBySkuIds(skuIds);
            if (Objects.equals(num,0)){
                //下架该商品
                ShopGoodsInfo goodsInfo=shopGoodsInfoService.getById(shopGoodsId);
                goodsInfo.setStatus(false);
                shopGoodsInfoService.updateById(goodsInfo);
            }
        }
    }
}

